﻿using System.Collections.Concurrent;
using RpcClient.Interface;
using RpcExtend.DAL;
using RpcExtend.Model;
using RpcHelper;

namespace RpcExtend.Collect.Collect
{
    [RpcClient.Attr.ClassLifetimeAttr(RpcClient.Attr.ClassLifetimeType.单例)]
    internal class RemoteServerCollect : IRemoteServerCollect
    {
        private static readonly ConcurrentDictionary<long, RemoteServerConfig> _RemoteConfig = new ConcurrentDictionary<long, RemoteServerConfig>();
        private readonly IUnityCollect _Unity;
        public RemoteServerCollect(IUnityCollect unity)
        {
            this._Unity = unity;
        }

        public RemoteServerConfig GetServer(long serverId)
        {
            if (_RemoteConfig.TryGetValue(serverId, out RemoteServerConfig server))
            {
                return server;
            }
            server = _Unity.Resolve<IRemoteServerConfigDAL>().GetServer(serverId);
            if (server == null)
            {
                throw new ErrorException("rpc.server.config.not.find");
            }
            _RemoteConfig.TryAdd(serverId, server);
            return server;
        }
    }
}
